Page({

  data: {
    
    animationData: {},
    showShade:false,
    showDownloadCard:false,
    // 状态栏高度
    statusBarHeight: wx.getStorageSync('statusBarHeight') + 'px',
    // 导航栏高度
    navigationBarHeight: wx.getStorageSync('navigationBarHeight') + 'px',
    // 胶囊按钮高度
    menuButtonHeight: wx.getStorageSync('menuButtonHeight') + 'px',
    // 导航栏和状态栏高度
    navigationBarAndStatusBarHeight:
      wx.getStorageSync('statusBarHeight') +
      wx.getStorageSync('navigationBarHeight') +
      'px',
    tabs: [],
    activeTab: 0,
    allFileList:[],
    selectedFile:[],
    score:0,
    tabbarHeight:"",
    paddingTop:"",
    list: [
      {
        "text": "首页",
        
        "iconPath": "/images/home.png",
        "selectedIconPath": "/images/home_active.png"
      },
      {
        "text": "文库",
        
        "iconPath": "/images/library.png",
        "selectedIconPath": "/images/library_active.png"
      },
      {
        "text": "社区",
        
        "iconPath": "/images/community.png",
        "selectedIconPath": "/images/community_active.png"
      },
      {
        "text": "我的",
        
        "iconPath": "/images/user.png",
        "selectedIconPath": "/images/user_active.png"
      }
    ]
  },

  
  onLoad(options) {
    let index = options.pageIndex
    this.setData({pageIndex : index})
    this.getLibraryList()
    
  },
  init (option) {
    let app = getApp()
    wx.request({
      url: app.globalData.url + '/file/listcategory',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: result => {
        let categoryList = result.data.data
        let tabs = [{'title':'推荐','fileList':[]}]
        for(let i = 0; i < categoryList.length; ++i){
          tabs.push({'title':categoryList[i].category,'fileList':[]})
        }
        this.setData({tabs})
      }
    })
  },
  async getLibraryList () {
    await this.init()
    let app = getApp()
    wx.request({
      url: app.globalData.url + '/file/listfile',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: result => {
        
        let code = result.statusCode.toString()
        if (code.startsWith('2')) {
          let fileList = result.data.data
          this.setData({allFileList:fileList})
          let tabs = this.data.tabs
          tabs[0].fileList = fileList
          for(let i = 0; i < fileList.length; ++i){
            let category = fileList[i].category
            tabs[category].fileList.push(fileList[i])
          }
          this.setData({tabs})
        } else {
          wx.showToast({
            title: '请求失败！',
            icon: 'error',
            duration: 2000
          })   
        }
        
      },
      fail:result =>{
        wx.showToast({
          title: '请求失败！',
          icon: 'error',
          duration: 2000
        })        
      }
    })
  },
  
  onTabClick(e) {
    const index = e.detail.index
    this.setData({ 
      activeTab: index 
    })
  },
  onChange(e) {
    const index = e.detail.index
    this.setData({ 
      activeTab: index 
    })
  },
  goToSearch:function () {
    wx.navigateTo({
      url: '/pages/search/search?source=library',
    })
  },
  onReady: function () {
    this.animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease',
    })
    
  },
  translate: function (event) {

    let app = getApp()
    if(app.globalData.newUser){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1000
      })  
    }else{
      wx.hideTabBar()
      let tabbarHeight = wx.getStorageSync('tabBarHeight')
      let height = wx.getSystemInfoSync().windowHeight;
      this.setData({
        showShade:true,
        showDownloadCard:true
      })
      var obj = this.createSelectorQuery();
      obj.select('.window').boundingClientRect((rect)=> {
        let paddingTop = Math.round((height * 0.50 - rect.height) / 2)
        this.setData({
          paddingTop:paddingTop + "px",
        })

      }).exec();
      this.animation.translateY(-height * 0.50).step()
      this.setData({animation: this.animation.export()})
      let app = getApp()
      this.setData({score: app.globalData.userInfo.score})
      let id = event.currentTarget.dataset.fileId
      let allFileList = this.data.allFileList
      for(let i = 0; i < allFileList.length; ++i){
        if(allFileList[i].id == id){
          this.setData({selectedFile:allFileList[i]})
        }
      }
      let score = app.globalData.userInfo.score
      let neededScore = this.data.selectedFile.score
      let selectedFile = this.data.selectedFile
      if(score < neededScore){
        selectedFile.panUrl = "积分不足，赶快做题赚取积分吧。"
        this.setData({selectedFile:selectedFile})
      }
    }
  },
  
  hide:function(){
    let height = wx.getSystemInfoSync().windowHeight;
    this.setData({showShade:false})
    this.animation.translateY(height * 0.50).step()
    this.setData({animation: this.animation.export()})
    setTimeout(() => {
      this.setData({showDownloadCard:false})
    }, 500)
    wx.showTabBar()
    
  },
  copyLink:function(event){
    let id = event.currentTarget.dataset.id
    let app = getApp()
    let score = app.globalData.userInfo.score
    let neededScore = this.data.selectedFile.score
    if(score < neededScore){
      wx.showToast({
        title: '积分不足',
        icon: 'none',
        duration: 1000
      })      
    }else{
      score = score - neededScore
      app.globalData.userInfo.score = score
      wx.setClipboardData({
        data: this.data.selectedFile.panUrl,
        success :res => {
          wx.getClipboardData({
            success (res) {
              console.log(res.data) // data
            }
          })
          wx.showToast({
            title: '拷贝成功',
            icon: 'success',
            duration: 1000
          })    
          this.setData({showDownloadCard:false})
          this.setData({showShade:false})
          wx.request({
            url: app.globalData.url + '/file/mark',
            data: {
              bookId:id,
              counts:1,
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: result => {

            }
          })
          wx.request({
            url: app.globalData.url + '/user/updateselective',
            data: {
              score: app.globalData.userInfo.score,
              openId:app.globalData.userInfo.openid,
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: result => {
              console.log(result.data)
            }
          })
        }
      })
    }
  },
  goToDetail:function(){
    wx.navigateTo({
      url: '/pages/download/download',
    })
  },
  mark:function(event){
    let id = event.currentTarget.dataset.id
    let app = getApp()
    wx.request({
      url: app.globalData.url + '/file/mark',
      data: {
        bookId:id,
        mark:1,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: result => {
        wx.showToast({
          title: '标记成功',
          icon: 'success',
          duration: 1000
        })   
      }
    })
  },
  
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
  },
  onHide: function () {

  },
  onUnload: function () {

  },
  async onPullDownRefresh() {
    await this.getLibraryList()
    
    wx.stopPullDownRefresh()
  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {

  }
})